#include "udp_proto.h"

int main (void)
{
	struct sockaddr_in local_addr, remote_addr;
	socklen_t  remote_addr_len;
	struct msg_t buf;
	ssize_t cnt;
	int fd = socket (AF_INET, SOCK_DGRAM, 0);
	if (-1 == fd) {
		perror ("socket()");
		exit (1);
	}
	//绑定本地地址
	local_addr.sin_family  = AF_INET;
	local_addr.sin_port = htons (atoi(SERVER_PORT));
	//将点分十进制的地址字符串转换为地址结构体
	inet_aton (SERVER_IP, &local_addr.sin_addr);
	if (-1 == bind (fd, (struct sockaddr *)&local_addr, sizeof (local_addr)))
	{
		perror ("bind()");
		goto ERROR;
	}
	//注意：在发送数据之前需要先确定好地址长度
	remote_addr_len  = sizeof (remote_addr);
	while (1) {
		cnt = recvfrom (fd, &buf, sizeof(struct msg_t), 0, (void *)&remote_addr, &remote_addr_len);
		if (-1 == cnt) {
			perror ("recvfrom ()");
			goto ERROR;
		}

		printf ("***********debug**************\n");
		printf ("ip:%s, prot:%d\n", inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));
		printf ("msg id:%d  msg name:%s\n", buf.id, buf.name);
		printf ("***********debug**************\n");
	}
	close (fd);
	return 0;
ERROR:
	close (fd);
}
